<template>
  <div class="commentsDig">
    <div class="comments">
      <div class="modal-detail-content">
        <!-- 附件列表 -->
        <div v-loading="attachLoading" class="task-comment-activity" style="border: 0;">
          <div class="modal-row-header">
            <ul class="toggle-tab">
              <li>
                <i class="el-icon-user" />{{ $t('附件') }}
              </li>
            </ul>
          </div>
          <div class="modal-row-content">
            <ul class="member-list comment-item" style="display: block;">
              <li v-for="(file, index) in fileList" :key="index" style="font-size: 13px;line-height: 30px;">
                <span v-if="configDownloadEnabled" style="float: right;color: #4e8afa;cursor: pointer;" @click="download(file.id)">
                  <i class="el-icon-download" /> {{ $t('下载') }}
                </span>
                <span style="float: right;color: #4e8afa; margin-right: 10px;cursor: pointer;" @click="version(file.id)">
                  <i class="el-icon-time" /> {{ $t('版本') }}
                </span>
                <span v-if="currentUser === file.createBy.id" style="float: right;color: #4e8afa; margin-right: 10px;cursor: pointer;" @click="onlinePreview(file.id, 'review')">
                  <i class="el-icon-edit" /> {{ $t('编辑') }}
                </span>
                <span class="avatar-default" style="color: #4e8afa;cursor: pointer;" @click="onlinePreview(file.id, 'view')">
                  <i class="el-icon-document" />
                  {{ $t(file.name) }}
                </span>
              </li>
            </ul>
          </div>
        </div>
        <!-- 参与人 -->
        <div v-loading="userIdsLoading" class="task-comment-activity">
          <div class="modal-row-header">
            <ul class="toggle-tab">
              <li>
                <i class="el-icon-user" />{{ $t('参与人') }}
              </li>
            </ul>
          </div>
          <div class="modal-row-content">
            <ul class="member-list comment-item" style="display: block;">
              <li v-for="(user, index) in userList" :key="index" class="ng-star-inserted">
                <!-- del -->
                <i
                  v-if="dragFormCreateById !== user.id"
                  class="el-icon-error"
                  @click="eliminateParticipants(user.id)"
                />
                <i
                  v-else
                  class="el-icon-error"
                />
                <!--  -->
                <div>
                  <el-tooltip class="item" effect="dark" :content="$t(user.nickName)" placement="top">
                    <span
                      v-if="user.avatar !== null"
                      class="avatar-default"
                    >
                      <el-image
                        v-if="user.avatar !== null"
                        :src="user.avatar"
                      />
                    </span>
                    <span v-else class="avatar-default">
                      <i class="el-icon-user" />
                    </span>
                  </el-tooltip>
                  <div
                    :style="{ color: (currentUser === user.id ? '#FFC107' : 'black') }"
                    class="userName"
                  >{{ $t(user.nickName) }}</div>
                </div>
              </li>
              <li class="ng-star-inserted">
                <span>
                  <i class="el-icon-plus" style="font-weight: bolder;" @click="resetParticipant()" />
                </span>
              </li>
            </ul>
          </div>
        </div>
        <!-- 评论 -->
        <div class="task-comment-activity" style="clear: both;">
          <div class="modal-row-header">
            <ul class="toggle-tab">
              <li>
                <i class="el-icon-chat-dot-round" />{{ $t('评论') }}
              </li>
            </ul>
          </div>
          <div v-loading="commentsLoading" class="modal-row-content">
            <div v-for="(context, index) in contextList" :key="index" class="borderBottom">
              <!-- 系统提示 -->
              <p v-if="context.type === '0'" class="log">
                <span>{{ context.createTime }}: {{ globalization($t(context.context)) }}</span>
              </p>
              <!-- 用户平路 -->
              <div v-if="context.type === '1'" class="comment-item">
                <!-- 头像 -->
                <span v-if="context.avatar !== null" class="avatar-icon">
                  <el-image :src="context.avatar" style="background: #ff000000" />
                </span>
                <span v-else class="avatar-icon" style="background-color:#84e17e;">
                  <span>{{ $t(context.nickName) }}</span>
                </span>
                <!-- 评论正文 -->
                <div class="comment-item-wrap">
                  <div class="comment-item-meta">
                    <a class="comment-name">
                      <span class="ng-binding">{{ $t(context.nickName) }}</span>
                    </a>
                    <span class="comment-time ng-binding">{{ context.createTime }}</span>
                    <i
                      v-if="context.createBy.id === currentUser"
                      class="el-icon-close"
                      @click="delContext(context.id, context.createTime)"
                    />
                  </div>
                  <div class="comment-item-content" v-html="context.context" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-detail-footer">
        <comment-editor ref="commentEditorRef" @submit="submitContext" @elIconRefresh="elIconRefresh" />
      </div>
    </div>
    <!-- </el-dialog> -->
    <!-- 添加参与人  -->
    <el-dialog :title="$t('参与人')" :visible.sync="addContactLoading" :close-on-click-modal="false" width="40%" :destroy-on-close="true" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :inline="true" class="dataForm">
        <el-form-item :label="$t('参与人')" prop="remindUsers" class="maxUser">
          <UserSelect
            v-model="form.remindUsers"
            :multiple="true"
            clearable
            :placeholder="$t('选择用户')"
          />
        </el-form-item>
        <div style="text-align: right;">
          <el-button type="primary" @click="addContactMethod">{{ $t('确定') }}</el-button>
        </div>
      </el-form>
    </el-dialog>
    <!--操作版本页面-->
    <el-dialog :title="$t('版本')" :visible.sync="historicalFileLoading" :close-on-click-modal="false" width="80%" :destroy-on-close="true" append-to-body>
      <historicalFile ref="historicalFile" />
    </el-dialog>
    <!-- 预览附件 -->
    <OnlinePreview ref="OnlinePreview" :preview-tit="$t('版本')" />
  </div>
</template>

<script>
import { listDiscussCommentsAll, saveDiscussComments, delDiscussComments } from '@/api/file/discussComments/discussComments.js'
import { getAttachUserIdById, addCommenter, delCommenter, newDiscussionNotification } from '@/api/file/discussComments/discussUsersFiles.js'
import commentEditor from '@/components/CommentEditor'
import { downLoadFileOpen } from '@/utils/zipdownload'
import historicalFile from '@/views/file/document/library/historicalFile.vue'
export default {
  components: {
    commentEditor,
    historicalFile
  },
  data() {
    return {
      formOpen: false,
      commentsLoading: false,
      addContactLoading: false,
      attachLoading: false,
      userIdsLoading: false,
      historicalFileLoading: false,
      userList: [],
      fileList: [],
      contextList: [],
      currentUser: this.$store.state.user.userId,
      dragFormId: '',
      form: {
        remindUsers: []
      },
      rules: {
        remindUsers: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      overtimeTime: 5,
      dragFormCreateById: '',
      // 被讨论的单个文件Id
      discussFileId: '',
      // 全局下载开关
      configDownloadEnabled: true
    }
  },
  created() {
    if (this.$parent.form !== undefined) {
      const dataId = this.$parent.form.dataId
      if (dataId !== undefined && dataId !== '' && dataId !== null) {
        this.init(dataId)
      }
    }
    // 全局下载开关
    this.getConfigKeyToDownload('enable_download').then(response => {
      this.configDownloadEnabled = (response.msg === 'true')
    })
    this.$bus.$emit('async_done')
  },
  methods: {
    init(id) {
      var dataId = (this.isEmpty(id) ? '-999' : (typeof id === 'string' ? id : id.id))
      this.dragFormId = dataId
      this.formOpen = true
      // 获取附件和参与人
      this.getAttachUserIds(dataId)
      // 获取评论
      this.getComments(dataId)
      // 消息通知页面隐藏右侧
      this.$nextTick(() => {
        this.$parent.isComment = false
      })
    },
    // 获取附件和参与人
    getAttachUserIds(id) {
      var that = this
      that.userIdsLoading = true
      that.attachLoading = true
      getAttachUserIdById(id).then(response => {
        if (response.data !== null) {
          that.fileList = response.data.fileList
          that.userList = response.data.userList
          that.form.remindUsers = []
          that.userList.forEach(item => {
            that.form.remindUsers.push(item.id)
          })
          that.dragFormCreateById = response.data.createBy.id
        } else {
          this.fileList = []
          this.userList = []
          this.contextList = []
          that.$confirm(that.$t('当前文件不存在讨论,是否发起一个?'), that.$t('提示'), {
            confirmButtonText: that.$t('确定'),
            cancelButtonText: that.$t('取消'),
            type: 'info'
          })
          .then(function() {
            that.userIdsLoading = true
            that.attachLoading = true
            that.commentsLoading = true
            // 确定创建改文件的新讨论
            newDiscussionNotification(that.discussFileId).then(response => {
              console.log('创建讨论成功!')
              if (response.code === 200) {
                that.dragFormId = response.data
                that.msgSuccess(that.$t('创建成功!'))
                that.getAttachUserIds(response.data)
                that.getComments(response.data)
                that.$parent.$parent.discussionNoticeRefresh(response.data, that.discussFileId)
                return true
              }
            })
          })
          .catch(function() {
            // 取消
            that.$parent.$parent.commentsOpen = false
          })
        }
        that.userIdsLoading = false
        that.attachLoading = false
        that.commentsLoading = false
      })
    },
    // 获取评论
    getComments(id) {
      this.commentsLoading = true
      listDiscussCommentsAll({ parentId: id }).then(response => {
        if (response.code === 200 && response.data !== null) {
          this.contextList = response.data
        }
        this.commentsLoading = false
      })
    },
    // 保存评论, 提交后不加载遮盖层直接显示到页面 后台进行保存
    submitContext(context) {
      this.$nextTick(() => {
        this.$refs.commentEditorRef.emptyCommentContent()
      })
      // 判断当前用户是不是参与人 如果不是先添加到参与人
      var insertUserFlag = true
      this.userList.some(item => {
        if (item.id === this.$store.state.user.userId) {
          insertUserFlag = false
        }
      })
      if (insertUserFlag) {
        this.form.remindUsers = [this.$store.state.user.userId]
        this.addContactUser()
      }
      // 保存当前评论
      var row = {
        parentId: this.dragFormId,
        context: context,
        type: '1',
        avatar: this.$store.state.user.avatar,
        nickName: this.$store.state.user.name
      }
      // 后台保存
      this.commentsLoading = true
      saveDiscussComments(row).then(response => {
        row.createTime = this.dateFormat('yyy-MM-dd hh:mm:ss', new Date())
        row.id = response.data.id
        const createBy = {
          id: this.currentUser
        }
        row.createBy = createBy
        row.context = response.data.context
        this.contextList.push(row)
        this.thePageIsAtTheBottom()
        this.msgSuccess(this.$t('评论已发布'))
        this.commentsLoading = false
      })
    },
    // 刷新评论
    elIconRefresh() {
      this.getComments(this.dragFormId)
      this.thePageIsAtTheBottom()
    },
    // 删除不评论
    delContext(id, time) {
      var timeFlag = this.moreThanTheSpecifiedTime(time)
      if (timeFlag) {
        this.commentsLoading = true
        delDiscussComments(id).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('已删除!'))
            this.commentsLoading = false
            this.contextList.forEach((item, index) => {
              if (item.id === id) {
                this.contextList.splice(index, 1)
              }
            })
          } else {
            this.msgError(this.$t('删除失败!'))
          }
        })
      } else {
        this.msgError(this.$t('已超过可删除时限') + ' (' + this.overtimeTime + this.$t('分钟)'))
      }
    },
    // 让页面位于最底部 scrollHeight
    thePageIsAtTheBottom() {
      this.$nextTick(() => {
        try {
          var container = this.$el.querySelector('.modal-detail-content')
          container.scrollTop = container.scrollHeight
        } catch (e) {
          console.log(e)
        }
      })
    },
     // 添加前重置参与人
    resetParticipant() {
      this.form.remindUsers = []
      this.addContactLoading = true
    },
    // 添加参与人
    addContactMethod() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.addContactLoading = false
          this.userIdsLoading = true
          this.attachLoading = true
          if (!this.form.remindUsers.includes(this.currentUser)) {
            this.form.remindUsers.push(this.currentUser)
          }
          this.addContactUser()
        }
      })
    },
    // 添加参与人2
    addContactUser() {
      // 将新的用户组保存导数据库 到这吧我睡了
      addCommenter({ id: this.dragFormId, remindUsers: this.form.remindUsers.join(',') }).then(response => {
        if (response.code === 200 && response.data !== null) {
          this.userList = response.data.userList
        } else {
          this.msgError(this.$t('发生异常!'))
        }
        this.userIdsLoading = false
        this.init(this.dragFormId)
      })
    },
    // 请离参与人
    eliminateParticipants(userId) {
      var msg = ''
      var myFlag = false
      if (userId === this.currentUser) {
        msg = this.$t('离开当前评论, 是否继续?')
        myFlag = true
      } else {
        msg = this.$t('请离该参与人, 是否继续?')
      }
      this.$confirm(msg, this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        this.userIdsLoading = true
        delCommenter({ id: this.dragFormId, remindUsers: userId }).then(response => {
          if (response.code === 200 && response.data !== null) {
            this.userList = response.data.userList
            this.$message({
              type: 'success',
              message: this.$t('操作成功!')
            })
            if (myFlag) {
              this.formOpen = false
            } else {
              this.getComments(this.dragFormId)
            }
          } else {
            this.msgError(this.$t('发生异常!'))
          }
          this.userIdsLoading = false
        })
      }).catch(() => {
        console.log(this.$t('已取消删除'))
      })
    },
    // 预览附件
    onlinePreview(id, type) {
      this.$refs.OnlinePreview.onlinePreviewFile(id, type)
    },
    // 下载
    download(id) {
      downLoadFileOpen(id)
    },
    // 文件版本
    version(id) {
      this.historicalFileLoading = true
      this.$nextTick(() => {
        this.$refs.historicalFile.fileDirId = id
        this.$refs.historicalFile.initVersion()
      })
    },
    /* ********************* utils ************************* */
    // 格式化时间
    dateFormat(fmt, date) {
      var ret
      const opt = {
        'y+': date.getFullYear().toString(),
        'M+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'h+': date.getHours().toString(),
        'm+': date.getMinutes().toString(),
        's+': date.getSeconds().toString()
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (var k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')))
        }
      }
      return fmt
    },
    // 时间差
    moreThanTheSpecifiedTime(time) {
      var minute = this.overtimeTime
      // 如果时间格式是正确的，那下面这一步转化时间格式就可以不用了
      // 将-转化为/，使用new Date
      var dateBegin = new Date(time.replace(/-/g, '/'))
      // 获取当前时间
      var dateEnd = new Date()
      // 时间差的毫秒数
      var dateDiff = dateEnd.getTime() - dateBegin.getTime()
      // 计算出相差天数
      var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000))
      // 计算天数后剩余的毫秒数
      var leave1 = dateDiff % (24 * 3600 * 1000)
      // 计算出小时数
      var hours = Math.floor(leave1 / (3600 * 1000))
      // 计算相差分钟数
      var leave2 = leave1 % (3600 * 1000)
      // 计算小时数后剩余的毫秒数
      // 计算相差分钟数
      var minutes = Math.floor(leave2 / (60 * 1000))
      // 计算分钟数后剩余的毫秒数
      // var leave3 = leave2 % (60 * 1000)
      // var seconds = Math.round(leave3 / 1000)
      if (dayDiff > 0) {
        return false
      } else if (hours > 0) {
        return false
      } else {
        return minutes <= minute
      }
    },
    globalization(context) {
      if (context.includes('刚刚上传了文件')) {
        context = context.replace('刚刚上传了文件', this.$t('刚刚上传了文件'))
        context = context.replace('大家快来围观一下!', this.$t('大家快来围观一下!'))
        return context
      } else if (context.includes('更新了成员')) {
        return context.replace('更新了成员', this.$t('更新了成员'))
      } else if (context.includes('请离了成员')) {
        return context.replace('请离了成员', this.$t('请离了成员'))
      } else if (context.includes('创建人修改了文件')) {
        return context.replace('创建人修改了文件', this.$t('创建人修改了文件'))
      } else {
        return context
      }
    }
  }
}
</script>
<style scoped lang="scss">
.avatar-icon {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  line-height: 32px;
  font-size: 12px;
  vertical-align: middle;
  display: inline-block;
  color: #fff;
  text-align: center;
  overflow: hidden;
  cursor: pointer;
}
</style>
